import type { FC } from 'react';
import { useEffect, useState } from 'react';
import CInput from '../prefix-input';
import styles from './index.less';
import type moment from 'moment';
import CDate from '../prefix-date';
import classnames from 'classnames';
import dayjs from 'dayjs';
type ValueType = {
  price?: string | number;
  date?: moment.Moment;
};
interface Props {
  value?: ValueType;
  disabled?: boolean;
  onChange?: (value: ValueType) => void;
}
const Index: FC<Props> = ({ onChange, value, disabled }) => {
  const [val, setVal] = useState<ValueType>({
    price: undefined,
    date: undefined,
  });
  const update = (value) => {
    if (onChange) {
      onChange?.(value);
    } else {
      setVal(value);
    }
  };
  const onPriceChange = (evt) => {
    update({
      ...val,
      price: evt.target.value?.replace(/^(0+)|[^\d]+/g, ''),
    });
  };
  const onDateChange = (date) => {
    update({
      ...val,
      date,
    });
  };
  const disabledDate = (current) => {
    return current && current < dayjs().endOf('day');
  };
  useEffect(() => {
    if (value) {
      setVal(value);
    } else {
      setVal({
        price: undefined,
        date: undefined,
      });
    }
  }, [value]);
  return (
    <div className={classnames(styles.container, { [styles.opacity3]: disabled })}>
      <CInput
        className={styles.margin}
        value={val.price}
        onChange={onPriceChange}
        addonAfter="¥"
        disabled={disabled}
        prefixText="预售价"
      />
      <CDate
        value={val.date}
        onChange={onDateChange}
        disabled={disabled}
        prefixText="截止时间"
        isRange={false}
        placeholder="选择预售截止时间"
        disabledDate={disabledDate}
      />
    </div>
  );
};

export default Index;
